package com.rc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rc.annotation.Authorization;
import com.rc.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
//如果有多个这样的类时，可以通过Order指定执行顺序，数值越小执行优先级越高
@Order(value = 0)
public class InitSystemConfig implements CommandLineRunner, EnvironmentAware {

    @Autowired
    WebApplicationContext applicationContext;

    @Value("${spring.application.name}")
    private String serviceName;
    @Value("${com.rc.authorization}")
    private String authorization;

    /*
     * 在服务启动后执行，会在@Bean实例化之后执行，故如果@Bean需要依赖这里的话会出问题
     */
    @Override
    public void run(String... args) {



        //这里可以根据数据库返回结果创建一些对象、启动一些线程等
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();



        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {




            Map<String, Object> map1 = new HashMap<String, Object>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();

            map1.put("micro", serviceName);
            //获取@Authorization的方法
            if ( method.getMethod().getAnnotation(Authorization.class) != null) {
                map1.put("authorization", 1);
            }else {
                map1.put("authorization", 0);
            }

            PatternsRequestCondition p = info.getPatternsCondition();


            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            map1.put("method", method.getMethod().getName()); // 方法名
            map1.put("classMethod",  method.getMethod().getDeclaringClass().getName()+"."+method.getMethod().getName()); // 方法名
            map1.put("type", "GET");

            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }

            for (String url : p.getPatterns()) {

                map1.put("url",map1.get("type")+"/"+serviceName+   getStringForKey(url));
            }

            list.add(map1);
        }


        JSON json = (JSON) JSON.toJSON(list);
        ShardedJedis jedis = null;
        try {
            jedis = RedisClient.getRedisClient();
            jedis.set(serviceName,json.toString());
           /* for(Map<String, Object>objectMap : list){
                jedis.hset(objectMap.get("micro").toString() ,objectMap.get("type")+getStringForKey("/"+objectMap.get("micro").toString()+objectMap.get("url").toString()),objectMap.get("authorization").toString());
            }*/


        } catch (JedisConnectionException e) {
            // LOGGER.error("redis 链接异常: " + e.getMessage());
            //  counter();
        } catch (Exception e) {
            //  LOGGER.error("redis 异常: " + e.getMessage(), e);
        } finally {
            jedis.close();
        }



    }

    /*
     * 在SystemConfigDao实例化之后、@Bean实例化之前执行
     * 常用于读取数据库配置以供其它bean使用
     * environment对象可以获取配置文件的配置，也可以把配置设置到该对象中
     */
    @Override
    public void setEnvironment(Environment environment) {
        System.out.println("############");

    }


    public String getStringForKey(String url){

        String [] sub_url_array = url.split("/");
        String url2 ="";
        for(String d :sub_url_array ){

            if (d.contains("{")){
                d="*";
            }
            url2=url2+"/"+d;

        }

        return url2.substring(1,url2.length());
    }




}

